package com.feicheng.service.a;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.task.Cache;
import com.feicheng.common.util.DateUtils;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.*;
import com.feicheng.persistence.mapper.*;
import com.feicheng.persistence.service.*;
import com.feicheng.service.AsyncService;
import com.feicheng.wxapi.pay.WxAppPayBean;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import jakarta.annotation.PostConstruct;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class FYyService {

    @Autowired
    IAstoreService storeService;

    @Autowired
    IAdzService dzService;

    @Autowired
    IAroomService roomService;

    @Autowired
    IAroomyyjlService yyjlService;

    @Autowired
    IAroomyyjlitemService yyjlitemService;

    @Autowired
    IAroomhourlypricesService aroomhourlypricesService;

    @Autowired
    IAjiaolianService jiaolianService;

    @Autowired
    IAmountService amountService;

    @Autowired
    IAroompjService aroompjService;

    @Autowired
    IAkechengService akechengService;

    @Autowired
    IAkechengitemService akechengitemService;

    @Autowired
    IAkechengskjlService akechengskjlService;

    @Autowired
    IAclientbmService aclientbmService;

    @Autowired
    IAzjService azjService;

    @Autowired
    IAcommissionService acommissionService;

    @Autowired
    IAcommissionitemService acommissionitemService;

    @Autowired
    AsyncService asyncService;

    @Autowired
    WxAppPayBean wxAppPayBean;

    @Autowired
    Cache cache;

    private String appid;

    private BigDecimal commissionproportion;

    @PostConstruct
    private void init() {
        Asetting asetting = cache.getObject("Asetting", Asetting.class);
        appid = asetting.getJappid();
        commissionproportion = asetting.getCommissionproportion();
    }

    @Transactional
    public synchronized void hxYyjlitem() {
        LocalDate now = LocalDate.now();
        // 核销昨天没有使用的记录
        QueryWrapper<Aroomyyjlitem> qw = new QueryWrapper<>();
        qw.le("cd", now);
        qw.eq("statu", "U");
        List<Aroomyyjlitem> items = yyjlitemService.list(qw);
        for (Aroomyyjlitem item : items) {
            item.setStatu("X");
        }
        yyjlitemService.updateBatchById(items);
    }

    @Transactional
    public synchronized void kaishiYyjl() {
        LocalDate now = LocalDate.now();
        // 核销昨天没有使用的记录
        QueryWrapper<Aroomyyjl> qw = new QueryWrapper<>();
        qw.eq("rn", 1);
        qw.eq("tflg", "P");
        qw.le("cd", now);

        AroomyyjlMapper aroomyyjlMapper = (AroomyyjlMapper) yyjlService.getBaseMapper();
        List<JSONObject> yyjls = aroomyyjlMapper.getYyjlWithMinDtet(qw);
        yyjls.forEach(obj -> {
            String statu = obj.getString("statu");

            if ("U".equals(statu)) {
                Aroomyyjl t = new Aroomyyjl();
                t.setRmorderid(obj.getString("rmorderid"));
                t.setTflg("S");
                yyjlService.updateById(t);
            }
        });
    }

    @Transactional
    public synchronized void wanchengYyjl() {
        LocalDate now = LocalDate.now();
        // 核销昨天没有使用的记录
        QueryWrapper<Aroomyyjl> qw = new QueryWrapper<>();
        qw.eq("rn", 1);
        qw.eq("tflg", "S");
        qw.lt("cd", now);

        AroomyyjlMapper aroomyyjlMapper = (AroomyyjlMapper) yyjlService.getBaseMapper();
        List<JSONObject> yyjls = aroomyyjlMapper.getYyjlWithMaxDtet(qw);
        yyjls.forEach(obj -> {
            String statu = obj.getString("statu");

            if (!"U".equals(statu)) {
                Aroomyyjl t = new Aroomyyjl();
                t.setRmorderid(obj.getString("rmorderid"));
                t.setTflg("F");
                yyjlService.updateById(t);
            }
        });
    }

    @Transactional
    public synchronized void jiesuanYyjl() {
        LocalDate now = LocalDate.now();
        LocalDate nowBefor30D = now.minusDays(30);
        QueryWrapper<Aroomyyjl> qw = new QueryWrapper<>();
        qw.eq("rn", 1);
        qw.eq("tflg", "F");
        qw.lt("cd", nowBefor30D);

        AroomyyjlMapper aroomyyjlMapper = (AroomyyjlMapper) yyjlService.getBaseMapper();
        List<JSONObject> yyjls = aroomyyjlMapper.getYyjlWithMaxDtet(qw);
        yyjls.forEach(obj -> {
            Aroomyyjl t = yyjlService.getById(obj.getString("rmorderid"));
            t.setTflg("G");
            yyjlService.updateById(t);

            if (t.getRmorderid().startsWith("YYJLZY")) {

            } else {
                Astore astore = storeService.getById(obj.getString("storeid"));
                Adz adz = dzService.getById(astore.getDzid());
                Amount amount = amountService.getById(adz.getOpenid());
                amount.setAmount(amount.getAmount() + obj.getInteger("amont"));
                amountService.updateById(amount);
            }

        });

    }

    /**
     * 取得预约记录ITEM
     * @param param
     * @return
     */
    public JSONObject getYyjlItem(JSONObject param) {
        JSONObject result = new JSONObject();

        QueryWrapper<Aroomyyjlitem> qw = new QueryWrapper<>();

        String storeid = param.getString("storeid");
        if(StringUtils.hasLength(storeid)) {
            qw.eq("aroomyyjl.storeid", storeid);
        }

        String roomid = param.getString("roomid");
        if(StringUtils.hasLength(roomid)) {
            qw.eq("aroomyyjlitem.roomid", roomid);
        }

        String jlid = param.getString("jlid");
        if(StringUtils.hasLength(jlid)) {
            qw.eq("aroomyyjl.jlid", jlid);
        }

        String tflg = param.getString("tflg");
        if(StringUtils.hasLength(tflg)) {
            qw.eq("aroomyyjl.tflg", tflg);
        }

        Boolean pflg = param.getBoolean("pflg");
        if(pflg != null) {
            qw.eq("aroomyyjl.pflg", pflg);
        }

        String kcitemid = param.getString("kcitemid");
        if(StringUtils.hasLength(kcitemid)) {
            if ("null".equals(kcitemid)) {
                qw.and(q -> {
                    q.or().isNull("aroomyyjlitem.kcitemid");
                    q.or().eq("aroomyyjlitem.kcitemid", "");
                });
            } else {
                qw.eq("aroomyyjlitem.kcitemid", kcitemid);
            }
        }

        String sd = param.getString("sd");
        if(StringUtils.hasLength(sd)) {
            try {
                LocalDate s = LocalDate.parse(sd, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                qw.ge("aroomyyjlitem.cd", s);
            } catch (Exception e) {

            }
        }

        String ed = param.getString("ed");
        if(StringUtils.hasLength(ed)) {
            try {
                LocalDate e = LocalDate.parse(ed, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                qw.le("aroomyyjlitem.cd", e);
            } catch (Exception e) {

            }
        }

        AroomyyjlitemMapper aroomyyjlitemMapper = (AroomyyjlitemMapper) yyjlitemService.getBaseMapper();
        List<JSONObject> items = aroomyyjlitemMapper.getItems(qw);
        result.put("aroomyyjlitems", items);

        return result;
    }

    @Transactional
    public JSONObject cancel(JSONObject param) {

        Aroomyyjl aroomyyjl = param.getObject("aroomyyjl", Aroomyyjl.class);

        QueryWrapper<Aroomyyjl> qw = new QueryWrapper<>();
        qw.eq("rmorderid", aroomyyjl.getRmorderid());
        qw.eq("rn", 1);
        qw.eq("tflg", "P");

        AroomyyjlMapper aroomyyjlMapper = (AroomyyjlMapper) yyjlService.getBaseMapper();
        List<JSONObject> yyjls = aroomyyjlMapper.getYyjlWithMinDtet(qw);

        if (null == yyjls && yyjls.size() == 0) {
            throw new SystemException("当前预约记录不满足取消条件");
        }

        JSONObject obj = yyjls.get(0);

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nowBefor = now.minusHours(3);
        LocalDate cd = LocalDate.parse(obj.getString("cd"), Constant.yyyyMMdd);
        String cdtStr = new StringBuilder(cd.format(Constant.yyyyMMdd))
                .append(" ")
                .append(obj.getString("st"))
                .toString();
        LocalDateTime cdt = LocalDateTime.parse(cdtStr, Constant.yyyyMMddHHmmss);
        if (!cdt.isAfter(nowBefor)
                && "U".equals(obj.getString("statu"))) {
            aroomyyjl.setTflg("C");
            yyjlService.updateById(aroomyyjl);

            QueryWrapper<Aroomyyjlitem> qwitem = new QueryWrapper<>();
            qwitem.eq("rmorderid", aroomyyjl.getRmorderid());
            yyjlitemService.remove(qwitem);

            Ajiaolian jiaolian = jiaolianService.getById(aroomyyjl.getJlid());
            Amount amount = amountService.getById(jiaolian.getOpenid());
            amount.setAmount(amount.getAmount() + aroomyyjl.getAmont());
            amountService.updateById(amount);
            param.put("amount", amount);
            param.put("aroomyyjl", aroomyyjl);
        } else {
            throw new SystemException("距离开始时间已经不足3小时，无法取消");
        }

        return param;
    }

    private Long yyitemCount(String itemid) {
        Long result = 0L;
        Aroomyyjlitem item = yyjlitemService.getById(itemid);
        if (null != item) {
            result = 1L;
        }
        return result;
    }

    /**
     * 新增预约记录
     * @param param
     * @return
     */
    @Transactional
    public JSONObject newYyjl(JSONObject param) {
        JSONObject result = new JSONObject();

        String storeid = param.getString("storeid");
        if (!StringUtils.hasLength(storeid)) {
            throw new SystemException("门店必须指定");
        }

        String roomid = param.getString("roomid");
        if (!StringUtils.hasLength(roomid)) {
            throw new SystemException("房间必须指定");
        }

        String jlid = param.getString("jlid");
        if (!StringUtils.hasLength(jlid)) {
            throw new SystemException("老师必须指定");
        }
        Ajiaolian jiaolian = jiaolianService.getById(jlid);

        String yyjlid = StringGenerator.getID("YYJL");
        JSONArray itemids = new JSONArray();
        List<Aroomyyjlitem> yyjlitems = new ArrayList<>();
        synchronized (roomid.intern()) {
            Aroomyyjl aroomyyjl = new Aroomyyjl();
            aroomyyjl.setRmorderid(yyjlid);
            aroomyyjl.setCt(LocalDateTime.now());
            aroomyyjl.setRoomid(roomid);
            aroomyyjl.setJlid(jlid);
            aroomyyjl.setStoreid(storeid);
            aroomyyjl.setPflg(false);
            aroomyyjl.setTflg("P");

            JSONObject yyjlObj = param.getJSONObject("yyjls");


            Integer amount = 0;
            for(Iterator<String> it = yyjlObj.keySet().iterator();it.hasNext();) {
                String key = it.next();
                String cdStr = key.split("@")[0];
                JSONObject value = yyjlObj.getJSONObject(key);

                Aroomhourlyprices aroomhourlyprices = value.getObject("aroomhourlyprices", Aroomhourlyprices.class);
                String itemid = Aroomyyjlitem.ID(aroomhourlyprices.getHid(), cdStr);

                Long count = this.yyitemCount(itemid);
                if (count > 0) {
                    throw new SystemException("当前预约时间段有冲突，请重新选择。");
//                    continue;
                }

                Aroomyyjlitem aroomyyjlitem = new Aroomyyjlitem();
                aroomyyjlitem.setItemid(itemid);
                aroomyyjlitem.setRmorderid(aroomyyjl.getRmorderid());
                aroomyyjlitem.setRoomid(roomid);
                aroomyyjlitem.setCd(LocalDate.parse(cdStr, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                aroomyyjlitem.setSt(aroomhourlyprices.getSt());
                aroomyyjlitem.setEt(aroomhourlyprices.getEt());
                aroomyyjlitem.setHid(aroomhourlyprices.getHid());
                aroomyyjlitem.setHp(JSONObject.toJSONString(aroomhourlyprices));
                aroomyyjlitem.setPrice(aroomhourlyprices.getPrice());
                aroomyyjlitem.setStatu("U");
                amount += aroomhourlyprices.getPrice();
                yyjlitems.add(aroomyyjlitem);
                itemids.add(itemid);

            }
            aroomyyjl.setAmont(amount);
            aroomyyjl.setSfje(amount);
            aroomyyjl.setYezfje(0);

            Amount amountJl = amountService.getById(jiaolian.getOpenid());
            if (amountJl.getAmount() >= amount) {
                aroomyyjl.setAmont(amount);
                aroomyyjl.setSfje(0);
                aroomyyjl.setYezfje(amount);
                aroomyyjl.setPflg(true);

                amountJl.setAmount(amountJl.getAmount() - amount);
                amountService.updateById(amountJl);
            } else {
                aroomyyjl.setAmont(amount);
                aroomyyjl.setSfje(amount - amountJl.getAmount());
                aroomyyjl.setYezfje(amountJl.getAmount());

                amountJl.setAmount(0);
                amountService.updateById(amountJl);
                PrepayWithRequestPaymentResponse prepayData =
                        wxAppPayBean.jsapi(
                                aroomyyjl.getRmorderid(),
                                "预约订单",
                                "/notice-url/"+aroomyyjl.getRmorderid(),
                                aroomyyjl.getSfje(),
                                jiaolian.getOpenid(),
                                "",
                                appid
                        );
                String prepayId = prepayData.getPackageVal().split("=")[1];
                aroomyyjl.setPrepaydata(JSONObject.toJSONString(prepayData));
                aroomyyjl.setPrepayid(prepayId);
            }

//            PrepayWithRequestPaymentResponse prepayData =
//                    wxAppPayBean.jsapi(
//                            aroomyyjl.getRmorderid(),
//                            "预约订单",
//                            "/notice-url/"+aroomyyjl.getRmorderid(),
//                            aroomyyjl.getSfje(),
//                            jiaolian.getOpenid(),
//                            "",
//                            appid
//                    );
//            String prepayId = prepayData.getPackageVal().split("=")[1];
//            aroomyyjl.setPrepaydata(JSONObject.toJSONString(prepayData));
//            aroomyyjl.setPrepayid(prepayId);
            yyjlService.save(aroomyyjl);
            yyjlitemService.saveBatch(yyjlitems);
            result.put("aroomyyjl", aroomyyjl);
            result.put("aroomyyjlitems", yyjlitems);
        }

        asyncService.runScheduler(() -> {
            synchronized (yyjlid.intern()) {
                Aroomyyjl aroomyyjl = yyjlService.getById(yyjlid);
                if (!aroomyyjl.getPflg()) {
                    yyjlitemService.removeByIds(itemids);
                    aroomyyjl.setTflg("C");
                    yyjlService.updateById(aroomyyjl);
                    return "未支付，预约取消";
                }

                Akecheng akecheng = new Akecheng();
                akecheng.setKcid(StringGenerator.getID("KC"));
                akecheng.setKcname("自行研习");
                akecheng.setPrice(0);
                akecheng.setZdrs(1);
                akecheng.setYbrs(1);
                akechengService.save(akecheng);

                Aclientbm bm = new Aclientbm();
                bm.setBmid(StringGenerator.getID("BM"));
                bm.setKcid(akecheng.getKcid());
                bm.setKcmc(akecheng.getKcname());
                bm.setJlid(jiaolian.getJlid());
                bm.setJlmc(jiaolian.getJlname());
                bm.setClientid("");
                bm.setKhnc("自行研习");
                bm.setCt(LocalDateTime.now());
                bm.setPflg(true);
                bm.setPrice(akecheng.getPrice());
                bm.setSyhycs(0);
                bm.setYezfje(0);
                bm.setSjzfje(akecheng.getPrice());
                aclientbmService.save(bm);

                for (Aroomyyjlitem aroomyyjlitem : yyjlitems) {
                    Akechengitem akechengitem = new Akechengitem();
                    akechengitem.setKcitemid(StringGenerator.getID("KCIT"));
                    akechengitem.setKcid(akecheng.getKcid());
                    akechengitem.setDt(aroomyyjlitem.getCd());
                    akechengitem.setSt(aroomyyjlitem.getSt());
                    akechengitem.setEt(aroomyyjlitem.getEt());
                    akechengitem.setRoomid(aroomyyjlitem.getRoomid());
                    akechengitem.setStoreid(aroomyyjl.getStoreid());
                    akechengitem.setItemname("自行研习");
                    akechengitem.setRmsyid(aroomyyjlitem.getItemid());
                    akechengitemService.save(akechengitem);
                    aroomyyjlitem.setKcitemid(akechengitem.getKcitemid());
                    yyjlitemService.updateById(aroomyyjlitem);

                    Akechengskjl skjl = new Akechengskjl();
                    skjl.setSkjlid(StringGenerator.getID("SKJL"));
                    skjl.setDt(akechengitem.getDt());
                    skjl.setSt(akechengitem.getSt());
                    skjl.setEt(akechengitem.getEt());
                    skjl.setCt(LocalDateTime.now());
                    skjl.setClientid(bm.getClientid());
                    skjl.setBmid(bm.getBmid());
                    skjl.setKcitemid(akechengitem.getKcitemid());
                    skjl.setStu("UD");
                    akechengskjlService.save(skjl);
                }

                return "已支付，预约成功";
            }

        }, 2, "预约记录支付核减：【"+yyjlid+"】");

        return result;
    }

    @Transactional
    public void payYyAfter(String rmorderid) {
        synchronized (rmorderid.intern()) {
            Aroomyyjl aroomyyjl = yyjlService.getById(rmorderid);
            if ("C".equals(aroomyyjl.getTflg())) {
                aroomyyjl.setTflg("C");
                yyjlService.updateById(aroomyyjl);
                Ajiaolian jiaolian = jiaolianService.getById(aroomyyjl.getJlid());
                Amount amount = amountService.getById(jiaolian.getOpenid());
                amount.setAmount(amount.getAmount() + aroomyyjl.getAmont());
                amountService.updateById(amount);
            } else {
                aroomyyjl.setPflg(true);
                Astore astore = storeService.getById(aroomyyjl.getStoreid());
                if (StringUtils.hasLength(astore.getZjid())) {
                    Azj azj = azjService.getById(astore.getZjid());
                    Acommission acommission = acommissionService.getById(azj.getCommissionid());

                    Acommissionitem acommissionitem = new Acommissionitem();
                    acommissionitem.setItemid(StringGenerator.getID("COIT"));
                    acommissionitem.setRmorderid(aroomyyjl.getRmorderid());
                    acommissionitem.setStoreid(aroomyyjl.getStoreid());
                    acommissionitem.setCommissionid(azj.getCommissionid());
                    acommissionitem.setAmont(aroomyyjl.getAmont());
                    acommissionitem.setProportion(commissionproportion);
                    acommissionitem.setCommission(commissionproportion.multiply(new BigDecimal(aroomyyjl.getAmont())).intValue());
                    acommissionitem.setZjid(astore.getZjid());
                    acommissionitem.setZjgsid(astore.getZjgsid());
                    acommissionitemService.save(acommissionitem);

                    acommission.setTotal(acommission.getTotal()+acommissionitem.getCommission());
                    acommissionService.updateById(acommission);
                }
                yyjlService.updateById(aroomyyjl);
            }

        }
    }

    public JSONObject getYyjlByDaily(JSONObject param) {

        JSONObject abc = new JSONObject();
        return abc;
    }


    /**
     * 以日期格式和时段取得预约记录ITEM
     * @param param
     * @return
     */
    public JSONObject getYyjlByRangeDate(JSONObject param) {
        JSONObject result = new JSONObject();

        String roomid = param.getString("roomid");
        String cds = param.getString("cds");
        String cde = param.getString("cde");
        if (!StringUtils.hasLength(roomid)) {
            throw new SystemException("房间必须指定");
        }

        AroomyyjlitemMapper aroomyyjlitemMapper = (AroomyyjlitemMapper) yyjlitemService.getBaseMapper();

        QueryWrapper<Aroomyyjlitem> qw = new QueryWrapper<>();
        qw.eq("roomid", roomid);

        if (StringUtils.hasLength(cds)) {
            qw.ge("cd", cds);
        }

        if (StringUtils.hasLength(cde)) {
            qw.le("cd", cde);
        }

        List<JSONObject> yyjls = aroomyyjlitemMapper.getYyjlForRangeDate(qw);


        for(Iterator<JSONObject> it = yyjls.iterator();it.hasNext();) {
            JSONObject item = it.next();
            String cdString = item.getJSONObject("aroomyyjlitem").getString("cd");
            String stString = item.getJSONObject("aroomyyjlitem").getString("st");
            String etString = item.getJSONObject("aroomyyjlitem").getString("et");

            StringBuilder timeKey = new StringBuilder(stString).append("-").append(etString);

            if (!result.containsKey(cdString)) {
                result.put(cdString, new JSONObject());
            }

            JSONObject dateitem = result.getJSONObject(cdString);


            if (!dateitem.containsKey(timeKey.toString())) {
                dateitem.put(timeKey.toString(), new JSONObject());
            }

            JSONObject timeitem = dateitem.getJSONObject(timeKey.toString());
            timeitem.put("cd", cdString);
            timeitem.put("checked", false);
            Aroomyyjlitem aroomyyjlitem = item.getObject("aroomyyjlitem", Aroomyyjlitem.class);
            timeitem.put("aroomyyjlitem", aroomyyjlitem);

            if (null != aroomyyjlitem) {
                Aroomhourlyprices aroomhourlyprices = JSONObject.parseObject(aroomyyjlitem.getHp(), Aroomhourlyprices.class);
                timeitem.put("aroomhourlyprices", aroomhourlyprices);
            }


            Aroomyyjl aroomyyjl = item.getObject("aroomyyjl", Aroomyyjl.class);
            timeitem.put("aroomyyjl", aroomyyjl);

            Akechengitem akechengitem = item.getObject("akechengitem", Akechengitem.class);
            timeitem.put("akechengitem", akechengitem);

            Akecheng akecheng = item.getObject("akecheng", Akecheng.class);
            timeitem.put("akecheng", akecheng);

            Ajiaolian ajiaolian = item.getObject("ajiaolian", Ajiaolian.class);
            timeitem.put("ajiaolian", ajiaolian);

        }

        QueryWrapper<Aroomhourlyprices> qwhp = new QueryWrapper<>();
        qwhp.eq("roomid", roomid);
        qwhp.orderByAsc("hid");
        List<Aroomhourlyprices> hps = aroomhourlypricesService.list(qwhp);

        if (null == hps || hps.isEmpty()) {
            throw new SystemException("该房间没有设置价格区间,无法预定。");
        }

        JSONObject hpObj = new JSONObject();
        for (Aroomhourlyprices hp : hps) {
            String ststr = hp.getSt().format(Constant.HHmm);
            String etstr = hp.getEt().format(Constant.HHmm);

            String key = new StringBuilder(ststr).append("-").append(etstr).toString();
            hpObj.put(key, hp);
        }


        LocalDate std = LocalDate.parse(cds, Constant.yyyyMMdd);
        LocalDate etd = LocalDate.parse(cde, Constant.yyyyMMdd);

        LinkedHashMap<String, LinkedHashMap<String, JSONObject>> dateRage =
                new LinkedHashMap<String, LinkedHashMap<String, JSONObject>>();
        while (!std.isAfter(etd)) {
            String dateKey = std.format(Constant.yyyyMMdd);

            if (!dateRage.containsKey(dateKey)) {
                dateRage.put(dateKey, new LinkedHashMap<String, JSONObject>());
            }

            LinkedHashMap<String, JSONObject> dateitem = dateRage.get(dateKey);

            hps.stream().forEach(hp -> {
                String ststr = hp.getSt().format(Constant.HHmm);
                String etstr = hp.getEt().format(Constant.HHmm);
                String key = new StringBuilder(ststr).append("-").append(etstr).toString();
                if (!dateitem.containsKey(key)) {
                    dateitem.put(key, new JSONObject());
                }

                if (result.containsKey(dateKey) && result.getJSONObject(dateKey).containsKey(key)) {
                    dateitem.put(key, result.getJSONObject(dateKey).getJSONObject(key));
                } else {
                    JSONObject timeitem = dateitem.get(key);
                    timeitem.put("cd", dateKey);
                    timeitem.put("checked", false);
                    timeitem.put("aroomhourlyprices", hp);
                }

            });

            std = std.plusDays(1L);
        }

        JSONObject abc = new JSONObject();
        abc.put("aa", dateRage);
        return abc;
    }


    /**
     * 预约记录分页查询 怡姐
     * @param param
     * @return
     */
    public JSONObject getYyjlByPage(JSONObject param) {
        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if(null == current || current < 0){
            current = 1;
        }
        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);

        QueryWrapper<JSONObject> queryWrapper = new QueryWrapper<>();

        //教练端预约记录
        String jlid = param.getString("jlid");
        if(StringUtils.hasLength(jlid)){
            queryWrapper.eq("aroomyyjl.jlid", jlid);
        }
        //店长端预约记录
        String storeid = param.getString("storeid");
        if(StringUtils.hasLength(storeid)){
            queryWrapper.eq("aroomyyjl.storeid", storeid);
        }

        //搜索 教练名，门店名，教练描述
        String jlname = param.getString("jlname");
        String sname = param.getString("sname");
        String ms = param.getString("ms");
        boolean hasSearchCondition = StringUtils.hasLength(jlname) || StringUtils.hasLength(sname) || StringUtils.hasLength(ms);
        if(hasSearchCondition){
            queryWrapper.and(qw -> {
                if(StringUtils.hasLength(jlname)){
                    qw.eq("ajiaolian.jlname", jlname);
                }
            }).or(qw -> {
                if(StringUtils.hasLength(sname)){
                    qw.eq("astore.sname", sname);
                }
            }).or(qw -> {
                if(StringUtils.hasLength(ms)){
                    qw.like("ajiaolian.ms", ms);
                }
            });
        }

        AroomyyjlMapper aroomyyjlMapper = (AroomyyjlMapper) yyjlService.getBaseMapper();
        page = aroomyyjlMapper.getYyjlWithJlByPage(page, queryWrapper);
        param.put("aroomyyjls", page);
        return param;
    }

    /**
     * 预约记录详细查询 怡姐
     * @param param
     * @return
     */
    public JSONObject getYyjl(JSONObject param) {
        String rmorderid = param.getString("rmorderid");
        if(!StringUtils.hasLength(rmorderid)){
            throw new SystemException("需要选择一个预约记录");
        }

        //场地预约记录
        Aroomyyjl aroomyyjl = yyjlService.getById(rmorderid);
        param.put("aroomyyjl", aroomyyjl);

        Aroom aroom = roomService.getById(aroomyyjl.getRoomid());
        param.put("aroom", aroom);

        Astore astore = storeService.getById(aroom.getStoreid());
        param.put("astore", astore);

        Adz adz = dzService.getById(astore.getDzid());
        param.put("adz", adz);

        //教练信息
        Ajiaolian ajiaolian = jiaolianService.getById(aroomyyjl.getJlid());
        param.put("ajiaolian", ajiaolian);

        QueryWrapper<Aroompj> pjqw = new QueryWrapper<>();
        pjqw.eq("jlid", aroomyyjl.getJlid());
        pjqw.eq("rmorderid", rmorderid);

        Aroompj aroompj = aroompjService.getOne(pjqw, false);
        param.put("aroompj", aroompj);

        //场地预约记录item信息 (+ 课程单节信息 + 门店名 + 房间名 + 店长)
        AroomyyjlitemMapper aroomyyjlitemMapper = (AroomyyjlitemMapper) yyjlitemService.getBaseMapper();
        QueryWrapper<JSONObject> qw = new QueryWrapper<>();
        qw.eq("aroomyyjlitem.rmorderid", rmorderid);
        List<JSONObject> aroomyyjlitems = aroomyyjlitemMapper.getItems(qw);
        param.put("aroomyyjlitems", aroomyyjlitems);

        //时段 价格
        JSONObject dates = new JSONObject();

        for (JSONObject item : aroomyyjlitems) {
            String cd = item.getString("cd");
            if (!dates.containsKey(cd)) {
                dates.put(cd, new JSONArray());
            }
            JSONArray itemsBydate = dates.getJSONArray(cd);
            itemsBydate.add(item);
        }

        param.put("dates", dates);
        return param;
    }

    /**
     * 预约记录修改 老蔡
     * @param param
     * @return
     */
    public JSONObject updateYyjl(JSONObject param) {
        Aroomyyjl aroomyyjl = param.getObject("aroomyyjl", Aroomyyjl.class);
        yyjlService.updateById(aroomyyjl);
        return param;
    }

}
